package com.lazyboyl.sharding.proxy.net.factory;

import com.lazyboyl.sharding.proxy.backend.service.CurrencyService;
import com.lazyboyl.sharding.proxy.net.decoder.MySqlPacketDecoder;
import com.lazyboyl.sharding.proxy.net.entity.ShardingLoginInfo;
import com.lazyboyl.sharding.proxy.net.frontend.FrontendAuthenticator;
import com.lazyboyl.sharding.proxy.net.frontend.FrontendConnection;
import com.lazyboyl.sharding.proxy.net.frontend.FrontendGroupHandler;
import com.lazyboyl.sharding.proxy.net.frontend.FrontendTailHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author linzef
 * @since 2021-06-29
 * 类描述： 前置handler，实现解包以及相关操作
 */
public class FrontHandlerFactory extends ChannelInitializer<SocketChannel> {

    private FrontConnectionFactory factory;

    private CurrencyService currencyService;

    public FrontHandlerFactory(ShardingLoginInfo shardingLoginInfo,CurrencyService currencyService) {
        factory = new FrontConnectionFactory(shardingLoginInfo);
        this.currencyService = currencyService;
    }


    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        // 获取当前的connection对象
        FrontendConnection connection = factory.getConnection();
        connection.setCurrencyService(currencyService);
        // 心跳handler
//        socketChannel.pipeline().addLast(new IdleStateHandler(10, 10, 10));
        // 根据mysql数据包的长度对其进行解码
        socketChannel.pipeline().addLast(new MySqlPacketDecoder());
        // navicat连接收集器，意味着有几个navicat连接了我们的服务器
        socketChannel.pipeline().addLast(new FrontendGroupHandler(connection));
        // navicate的核心实现，所有的增删改查全部在这个handler中实现
        socketChannel.pipeline().addLast(new FrontendAuthenticator(connection));
        // 异常的实现
        socketChannel.pipeline().addLast(new FrontendTailHandler(connection));
    }
}
